// pages/device-list/index.js
const app = getApp();
const api = app.api;
const wxutil = app.wxutil;
const pageSize = 16; // 每页显示条数

Page({
  data: {
    deviceList: [],
    pageDevice: 1,
    tabIndex: 0,
    tabsTop: 255,
    tabsFixed: false, // Tabs是否吸顶
    isEndDevice: false, // 话题是否到底
    loading: false,
    messageBrief: '',
    user: {},
  },

  onLoad() {},

  onShow() {
    this.getUser();
  },

  /**
   * 获取Tabs的高度
   */
  getTabsTop() {
    const navigateHeight = 56;
    const query = wx.createSelectorQuery();
    query.select("#tabs").boundingClientRect((res) => {
      this.setData({
        tabsTop: res.top - navigateHeight,
      });
    }).exec();
  },

  getUserDetail() {
    const userDetail = app.globalData.userDetail;
    // 授权用户使用userDetail作为用户信息
    if (userDetail) {
      const userId = userDetail.id;
      const url = api.userAPI + userId + "/";

      wxutil.request.get(url).then((res) => {
        if (res.data.code == 200) {
          const user = res.data.data;
          this.setData({
            user: user,
          });
          if (!this.data.user.is_register) {
            wx.navigateTo({
              url: "../user-edit/index",
            });
          }
        }
      });
    } else {
      wx.navigateTo({
        url: "../auth/index",
      });
    }
  },

  /**
   * 获取用户信息
   */
  getUser() {
    this.getDevice();
    this.getUserDetail();
  },

  getDevice(pageDevice = 1, size = pageSize) {
    const url = api.deviceAPI;
    const data = {
      size: size,
      page: pageDevice,
    };

    if (this.data.isEndDevice && pageDevice != 1) {
      return;
    }

    wxutil.request.get(url, data).then((res) => {
      if (res.data.code == 200) {
        const devices = res.data.data;
        const updatedDeviceList = pageDevice == 1 ? devices : this.data.deviceList.concat(devices);

        this.setData({
          pageDevice: devices.length == 0 && pageDevice != 1 ? pageDevice - 1 : pageDevice,
          loading: false,
          isEndDevice: devices.length < pageSize || (devices.length == 0 && pageDevice != 1),
          deviceList: updatedDeviceList,
        });
      }
    });
  },

  /**
   * 跳转到授权页面
   */
  gotoAuth() {
    wx.navigateTo({
      url: "/pages/auth/index",
    });
  },

  /**
   * 跳转详情页
   */
  gotoDetail(event) {
    const deviceId = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: "/pages/device-detail/index?deviceId=" + deviceId,
    });
  },

  /**
   * 触底加载
   */
  onReachBottom() {
    this.setData({
      loading: true,
    });
    const page = this.data.pageDevice;
    this.getDevice(page + 1);
  },

  onPageScroll(event) {
    if (event.scrollTop >= this.data.tabsTop) {
      this.setData({
        tabsFixed: true,
      });
    } else {
      this.setData({
        tabsFixed: false,
      });
    }
  },

  onShareAppMessage() {
    return {
      title: "设备列表",
      path: "/pages/device-list/index",
    };
  },
});
